package com.jumei.flume.common;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UrlUtils {
    /**
     * 解析page_type
     *
     * @param url
     * @return
     * @author admin
     * @since 2018年7月30日
     */
    public static String parsePageType(String url) {
        if (url == null) {
            return null;
        }
        if (Constants.excludePage.matcher(url).matches()) {
            // #140503 @2017-10-18
            return null;
        }

        for (Map.Entry<String, Pattern> entry : Constants.pagePatternMap.entrySet()) {
            Matcher m = entry.getValue().matcher(url);
            if (m.find()) {
                return entry.getKey();
            }
        }
        return null;
    }


    /**
     * 解析material_link中的type字段
     *
     * @param material_link
     * @return
     * @author admin
     * @since 2017年3月20日
     */
    public static HashMap<String, String> parsedMaterial_link(String material_link) {
        HashMap<String, String> sellType = Maps.newHashMap();
        int params_location = material_link.indexOf("?");
        if (params_location != -1) {
            Iterable<String> ones = Splitter.on("&").split(material_link.substring(params_location + 1));
            for (Iterator<String> iterator = ones.iterator(); iterator.hasNext(); ) {
                String one = (String) iterator.next();
                if (!Strings.isNullOrEmpty(one)) {
                    String[] each = one.split("=");
                    //异常URL，存在java.lang.ArrayIndexOutOfBoundsException
                    if (each.length >= 2) {
                        sellType.put(each[0], each[1]);
                    }
                }
            }
        }

        return sellType;
    }

}

